package com.zzxx.controller;

import com.github.pagehelper.PageInfo;
import com.zzxx.domain.Product;
import com.zzxx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @RequestMapping("findAll")
    public String findAll(Model model,
                          @RequestParam(name = "pageNum", required = true, defaultValue = "1") Integer pageNum,
                          @RequestParam(name = "pageSize", required = true, defaultValue = "4") Integer pageSize) {
        List<Product> list = productService.queryAll(pageNum, pageSize);
        PageInfo<Product> productPageInfo = new PageInfo<>(list);
        model.addAttribute("productPageInfo", productPageInfo);
        return "product-list";
    }

    @RequestMapping("findById")
    public String findById(Model model, @RequestParam(name = "id", required = true) String id){
        Product product = productService.queryById(id);
        model.addAttribute("product", product);
        return "product-add";
    }

    @RequestMapping("findDetail")
    public String findDetail(Model model, @RequestParam(name = "id", required = true) String id){
        Product product = productService.queryById(id);
        model.addAttribute("product", product);
        return "product-detail";
    }

    @RequestMapping(path = "updateById", method = RequestMethod.POST)
    public String updateById(Product product){
        productService.updateById(product);
        return "redirect:/product/findAll";
    }

    @RequestMapping(path = "insert", method = RequestMethod.POST)
    public String insert(Product product){
        productService.add(product);
        return "redirect:/product/findAll";
    }

    @RequestMapping(path = "deleteByIds", method = RequestMethod.POST)
    @ResponseBody
    public String deleteByIds(String[] ids){
        System.out.println(Arrays.toString(ids));
//        productService.deleteProduct(ids);
        return "ok";
    }
}
